package com.sum.tea.xinlian

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.SimpleAdapter
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.databinding.ActivityPathLocationBinding
import com.sum.tea.xinlian.viewmodel.SubPathViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.Locale

class SubPathActivity : BaseMvvmActivity<ActivityPathLocationBinding, SubPathViewModel>() {
    private var path: String? = Companion.sRoot
    private var list: MutableList<Map<String, Any?>>? = null
    private val imagemap: MutableMap<String, Int> = mutableMapOf()

    companion object {
        const val tag: String = "SaveFileDialog"
        const val sRoot: String = "/"
        const val sParent: String = ".."
        const val sFolder: String = "."
        const val sEmpty: String = ""
        private const val sOnErrorMsg = "No rights to access!"
    }

    override fun initView(savedInstanceState: Bundle?) {
        initializeImageMap()

        // 设置按钮点击事件
        mBinding.buttonSelect.setOnClickListener {
            val selectedPath = "$path/out.txt"
            val resultIntent = Intent().apply {
                putExtra("selected_path", selectedPath)
            }
            setResult(Activity.RESULT_OK, resultIntent)
            finish()
        }

        // 设置列表项点击事件
        mBinding.listViewPathlist.setOnItemClickListener { _, _, position, _ ->
            val item = list?.get(position) ?: return@setOnItemClickListener
            onItemClicked(item)
        }

        // 刷新文件列表
        refreshFileList()
    }

    private fun initializeImageMap() {
        imagemap[sRoot] = R.drawable.filedialog_root // 根目录图标
        imagemap[sParent] = R.drawable.filedialog_folder_up // 返回上一层的图标
        imagemap[sFolder] = R.drawable.filedialog_folder // 文件夹图标
        imagemap["bin"] = R.drawable.filedialog_file
        // imagemap["wav"] = R.drawable.filedialog_wavfile // 如果有WAV文件图标
        imagemap[sEmpty] = R.drawable.filedialog_root
    }

    private fun getImageId(s: String): Int {
        return when {
            imagemap.containsKey(s) -> imagemap[s]!!
            imagemap.containsKey(sEmpty) -> imagemap[sEmpty]!!
            else -> 0
        }
    }

    private fun getSuffix(filename: String): String {
        val index = filename.lastIndexOf('.')
        return if (index < 0) "" else filename.substring(index + 1)
    }

    private fun refreshFileList() {
        lifecycleScope.launch {
            val files = withContext(Dispatchers.IO) {
                try {
                    File(path).listFiles()
                } catch (e: Exception) {
                    null
                }
            }

            if (files == null) {
                Toast.makeText(this@SubPathActivity, sOnErrorMsg, Toast.LENGTH_SHORT).show()
                return@launch
            }

            if (list != null) {
                list!!.clear()
            } else {
                list = ArrayList()
            }

            val lfolders = mutableListOf<Map<String, Any?>>()
            val lfiles = mutableListOf<Map<String, Any?>>()

            if (path != sRoot) {
                // 添加根目录 和 上一层目录
                list?.add(
                    mapOf(
                        "name" to sRoot,
                        "path" to sRoot,
                        "img" to getImageId(sRoot)
                    )
                )
                list?.add(
                    mapOf(
                        "name" to sParent,
                        "path" to path,
                        "img" to getImageId(sParent)
                    )
                )
            }

            val suffixFilter: String? = null // 可以根据需要设置过滤的后缀，如 ".bin;"

            files.forEach { file ->
                if (file.isDirectory && file.listFiles() != null) {
                    // 添加文件夹
                    lfolders.add(
                        mapOf(
                            "name" to file.name,
                            "path" to file.path,
                            "img" to getImageId(sFolder)
                        )
                    )
                } else if (file.isFile) {
                    // 添加文件
                    val sf = getSuffix(file.name).lowercase(Locale.getDefault())
                    if (suffixFilter.isNullOrEmpty() || (sf.isNotEmpty() && suffixFilter.contains(".$sf;"))) {
                        lfiles.add(
                            mapOf(
                                "name" to file.name,
                                "path" to file.path,
                                "img" to getImageId(sf)
                            )
                        )
                    }
                }
            }

            list?.addAll(lfolders) // 先添加文件夹
            list?.addAll(lfiles) // 再添加文件

            // 初始化适配器
            val adapter = SimpleAdapter(
                this@SubPathActivity, list,
                R.layout.filedialogitem,
                arrayOf("img", "name", "path"),
                intArrayOf(
                    R.id.filedialogitem_img,
                    R.id.filedialogitem_name,
                    R.id.filedialogitem_path
                )
            )
            mBinding.listViewPathlist.adapter = adapter
        }
    }

    private fun onItemClicked(item: Map<String, Any?>) {
        val pt = item["path"] as? String ?: return
        val fn = item["name"] as? String ?: return

        path = when (fn) {
            sRoot, sParent -> {
                val fl = File(pt)
                fl.parent ?: sRoot
            }
            else -> {
                val fl = File(pt)
                if (fl.isDirectory) pt else path
            }
        }

        // 刷新文件列表
        mBinding.listViewPathlist.adapter?.let { adapter ->
            if (adapter is SimpleAdapter) {
                refreshFileList()
            }
        }
    }

}
